var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
const OSS = require('ali-oss');
const path = require('path');
const client = new OSS({
    region: 'oss-cn-beijing',
    accessKeyId: 'LTAI5t9P7C4aWcUsijzvpGUf',
    accessKeySecret: "FJfHFSD6bnnDSD55I4bMMA0g2F5P8q",
    bucket: 'hunshadock'
})
var { hunshaTypeModel, hunshaModel, imgModel } = require('../../model/model')
// 添加婚纱类别
router.post('/addhunshatype', (req, res) => {
    hunshaTypeModel.create(req.body)
    res.send({
        code: 200,
        msg: '添加成功'
    })
})
// 获取婚纱类别
router.get('/gethunshatype', async (req, res) => {
    let data = await hunshaTypeModel.find().lean()
    let obj = {}
    data.forEach(item => {
        obj[item._id] = item
    })
    let arr = []
    data.forEach(item => {
        if (!item['typeid']) {
            arr.push(item)
        } else {
            if (obj[item['typeid']] && !obj[item.typeid]['children']) {
                obj[item['typeid']]['children'] = []
            }
            obj[item['typeid']]['children'].push(item)
        }
    })
    // console.log(arr);
    res.send({
        code: 200,
        msg: '查询成功',
        data: arr
    })
})
router.post('/addhunshaitem', (req, res) => {
    hunshaModel.create(req.body)
    res.send({
        code: 200,
        msg: '添加成功'
    })
})
router.get('/gethunshaitem', async (req, res) => {
    let data = await hunshaModel.find().lean()
    res.send({
        code: 200,
        msg: '查询成功',
        data
    })
})



// 上传图片
router.post('/upload', async (req, res) => {
    let form = new multiparty.Form()
    form.uploadDir = "upload"
    form.parse(req, async (err, data, files) => {
        res.send({
            code: 200,
            msg: '添加图片成功',
            pic: files.file[0].path
        })
    })
})

// 图片表添加数据
router.post('/addimg', async (req, res) => {
    // console.log(req.body);
    try {
        // 上传文件到OSS，'object'是OSS中的文件名，'localfile'是本地文件的路径。
        let name = `${req.body.name}-${Date.now()}.${req.body.pic.split('.')[1]}`
        const uploadResult = await client.put(name, req.body.pic);
        console.log('上传成功:', uploadResult);
        // let data = await imgModel.create()
        listFiles(name,req.body._id);
    } catch (error) {
        console.error('发生错误:', error);
        // 在此处添加错误处理逻辑。
    }
    res.send({
        code: 200,
        msg: '添加图片成功',
        // data
    })
})
// 获取图片处理方法
async function listFiles(name,_id) {
    try {
        const result = await client.list({
            'max-keys': 100 // 你可以根据需要调整这个值
        });

        result.objects.forEach(async obj => {
            if(name===obj.name){
                let url=`https://${client.options.bucket}.${client.options.region}.aliyuncs.com/${obj.name}`
                await imgModel.create({url}).then(async res=>{
                    await hunshaModel.updateOne({_id},{$push:{imgid:res._id}})
                })
            }
        });
    } catch (e) {
        console.error('Failed to list files:', e);
    }
}
module.exports = router;
